<?php
namespace Partner\Controller;

use Utuo\BackgroundController;

class CustomerAdminController extends BackgroundController {
	
	private $tableNames; // 所有权限表的模型名
	
	protected $cid;
	
	public function _initialize(){
		$this->cid = I('cid');
		$this->setControllerTitle('管理员管理');
		$this->setActionTitle(array(
				'index' => '管理员列表',
				'add' => '添加管理员',
				'modify' => '修改管理员',
				'setRole' => '分配角色',
				'recycle' => '回收站',
	
		),'','cid='.$this->cid);
		$this->setActionNav(array(
				'index',
				'add',
				'recycle'
		));
		$this->assign("cid", $this->cid);
		$rbacMy = C('RBAC_MY');
		$this->tableNames = \Utuo\Rbac::getAuthModelNames( array('role' => $rbacMy['RBAC_ROLE_TABLE'], 'user' => $rbacMy['RBAC_USER_TABLE'], 'access' => $rbacMy['RBAC_ACCESS_TABLE'], 'node' => $rbacMy['RBAC_NODE_TABLE']) );
	}
	
	public function getLists($is_deleted) {
		$condition = array(
				'cid' => $this->cid,
				'is_deleted' => $is_deleted, );
		$customerAdminLists = M('CustomerAdmin')->where($condition)->select();
		$this->assign('customerAdminLists', $customerAdminLists);
		$this->display();
	}
	
	public function addAction() {
		$this->assign("customerAdmin", array( 'cid' => $this->cid ));
		$this->display();
	}
	
	public function modifyAction() {
		$customerAdmin = $this->getOneById("CustomerAdmin");
		$this->assign("customerAdmin", $customerAdmin);
		$this->display();
	}
	
	public function saveAction(){
		$this->submitPost('CustomerAdmin');
	}
	
	// 分配角色
	public function setRoleAction( $admin_cid ) {
		$cid = M("CustomerAdmin")->where("id={$admin_cid}")->getField("cid"); // 客户id
		$roles = M($this->tableNames['role'][1])->where("((pid={$this->aid} and cid=0) or (cid={$cid})) and is_deleted=%d", 0)->getField('id,name'); //合作商与客户的角色
		$curRoles = M($this->tableNames['user'][1])->where('admin_cid=%d',$admin_cid)->getField("role_id",true); // 当前用户已分配的角色
		$data['roleCheckbox']=\Utuo\Form::makeCheckbox($roles, $curRoles, 'role_id[]');
		$data['adminCid'] = $admin_cid;
		$this->assign("data",$data);
		$this->display();
	}
	
	public function saveRoleAction(){
		$adminCid = I('admin_cid');
		$role_ids = I('role_id');
		D($this->tableNames['user'][1])->where('admin_cid=%d', $adminCid)->delete();
		if( is_array( $role_ids ) ) {
			foreach ($role_ids as $v) {
				D($this->tableNames['user'][1])->add(array(
					'admin_cid' => $adminCid,
					'role_id' => $v
				));
			}
			$this->ajaxSuccess();
		}
		$this->ajaxError();
	}
	
	//是否开启角色分配
	public function isRoleAction($cid, $isrole) {
		M('CustomerAdmin')->where('id=%d',$cid)->setField("is_role",$isrole) ? $this->ajaxSuccess():$this->ajaxError();
	}
	
	// 删除数据
	public function removePostAction() {
		$this->ajaxRemove();
	}
	
	// 彻底删除
	public function deletePostAction() {
		$this->ajaxDelete();
	}
	
	// 恢复管理员
	public function restorePostAction() {
		$this->ajaxRestore();
	}
	
	public function setStatusPostAction() {
		$this->ajaxSetStatus();
	}
	
}